import React, {useEffect, useState} from 'react';
import {message, Modal, Space, Table, Tag} from "antd";
import TheButton from "@/components/TheButton/index.jsx";
import Add from "./component/add.jsx";
import Edit from "./component/edit.jsx";

import {apiUserPage, apiUserDel, apiUserState} from "@/api/system/user.js";
import logger from "redux-logger";

const {confirm} = Modal;

const Index = () => {
    const [dataSource, setDataSource] = useState();
    const [loading, setLoading] = useState(false);
    const ChildAddRef = React.createRef();
    const ChildEditRef = React.createRef();

    const [pageParams, setPageParams] = useState({
        pageNo: 1,
        pageSize: 10,
        total: 1
    })

    const columns = [
        {
            title: '序号',
            align: 'center',
            width: 80,
            key: 'no',
            render: (text, record, index) => {
                return (
                    //当前页数减1乘以每一页页数再加当前页序号+1
                    `${(pageParams.pageNo - 1) * (pageParams.pageSize) + (index + 1)}`
                )
            }
        },
        {
            title: '用户名',
            dataIndex: 'loginName',
            key: 'loginName',
            align: 'center'
        },
        {
            title: "姓名",
            align: 'center',
            dataIndex: "userName",
            key: "userName",
        },
        {
            title: "手机号",
            align: 'center',
            dataIndex: "userMobile",
            key: "userMobile",
        },
        {
            title: "角色",
            align: 'center',
            dataIndex: "roleNames",
            key: "roleNames",
            render: text => <div style={{
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                width: 200
            }}>{text === 'STORE' ? '门店管理员' : text}</div>,
            width: 200
        },
        {
            title: "创建时间",
            align: 'center',
            dataIndex: "createTime",
            key: "createTime"
        },
        {
            title: "创建人",
            align: 'center',
            dataIndex: "createUserName",
            key: "createUserName"
        },
        {
            title: "状态",
            align: 'center',
            key: 'status',
            render: (text, record) => (
                <>
                    {record.status === 'Y' && <Tag color="green">正常</Tag>}
                    {record.status === 'N' && <Tag color="red">冻结</Tag>}
                </>
            )
        },
        {
            title: "操作",
            key: "option",
            width: 220,
            render: (text, record) => (
                <Space size="small">
                    {
                        record.loginName !== 'admin' && record.status === 'Y' &&
                        <TheButton type="link" size='small' haspermi={['settings:user:freezon']}
                                   onClick={() => freeze('N', record)}>冻结</TheButton>
                    }
                    {
                        record.loginName !== 'admin' && record.status === 'N' &&
                        <TheButton type="link" size='small' haspermi={['settings:user:freezon']}
                                   onClick={() => freeze('Y', record)}>解冻</TheButton>
                    }
                    {
                        record.loginName !== 'admin' &&
                        <TheButton haspermi={['settings:user:edit']} type="link" size='small' auth={'user:update'}
                                   onClick={() => edit(record)}>编辑</TheButton>}
                    {
                        record.loginName !== 'admin' &&
                        <TheButton type="link" haspermi={['settings:user:delete']} size='small' auth={'user:delete'}
                                   onClick={() => delRow(record.userId)}>删除</TheButton>}
                </Space>
            ),
            fixed: 'right'
        }
    ]

    /**
     * @desc 获取表格数据
     * */
    const getList = (params) => {
        // this.setState({ loading: true })
        setLoading(true);
        apiUserPage({
            pageNo: params.pageNo,
            pageSize: params.pageSize
        }).then(res => {
            if (res.code === 0) {
                setDataSource(res.data);
                setLoading(false);
                setPageParams({
                    pageNo: res.pageNo,
                    pageSize: res.pageSize,
                    total: res.totalCount
                })
            }
        })
        // this.setState({ loading: false })
    }
    useEffect(() => {
        getList(pageParams)
    }, [])
    /**
     * @desc 分页切换
     * */
    const handleTableChange = async (pagination, filters, sorter) => {
        // `dataSource` is useless since `pageSize` changed
        if (pagination.pageSize !== pagination?.pageSize) {
            setDataSource([]);
        }
        await getList({
            pageNo: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total
        })
    }
    /**
     * @desc 冻结
     * */
    const freeze = (status, data) => {
        let str = status === 'N' ? '冻结' : '解冻';
        confirm({
            title: "警告",
            content: `确定要${str}吗？`,
            onOk: () => {
                apiUserState({
                    userId: data.userId,
                    status: status
                }).then(res => {
                    if (res.code === 0) {
                        message.success(`${str}成功`).then(() => {
                            getList(pageParams);
                        })
                    }
                })
            }
        });
    }
    /**
     * @desc 修改用户
     * */
    const edit = (data) => {
        ChildEditRef.current.openStatus(data.userId);
    }
    /**
     * @desc 删除事件
     * */
    const delRow = (userId) => {
        confirm({
            title: "警告",
            content: "确定要删除吗？",
            onOk: () => {
                apiUserDel({userId}).then(res => {
                    if (res.code === 0) {
                        message.success("删除成功")
                        getList(pageParams)
                    }
                })
            }
        });
    };
    return <Space direction={'vertical'} style={{display: 'flex'}}>
        <TheButton haspermi={['settings:user:add']} onClick={() => {
            ChildAddRef.current.openStatus();
        }}>
            新增用户
        </TheButton>
        <Table
            rowKey={(record) => record.userId}
            scroll={{y: 540}}
            bordered={true}
            dataSource={dataSource}
            columns={columns}
            loading={loading}
            onChange={handleTableChange}
            pagination={{
                position: ['bottomCenter'],
                current: pageParams.pageNo,
                pageSize: pageParams.pageSize,
                total: pageParams.total,
                showSizeChanger: false
            }}
        />
        <Add onRef={ChildAddRef} getList={getList}/>
        <Edit onRef={ChildEditRef} getList={getList}/>
    </Space>

};

export default Index;
